const { app, BrowserWindow, dialog, Menu, Tray, Error } = require('electron');
const path = require('path');
const url = require('url');
const trayIcon = path.join(__dirname, 'icon');
const DB = require('./DB/init');

let winObj = {};

function createWindow(data) {
    var winId = data.serviceId + '&' + data.projectId;
    let win;
    if (winObj.hasOwnProperty(winId)) {
        win = winObj[winId];
    };
    if (win) {
        if (hasWin.isMinimized()) hasWin.restore()
        hasWin.focus();
    } else {
        win = new BrowserWindow({
            width: 1200,
            height: 700,
            show: false,
            frame: false,
            webPreferences: {
                nodeIntegration: true
            }
        });
        win.webContents.on('did-finish-load', function () {
            win.webContents.send('dataJsonPort', JSON.stringify(data));
        });
        win.once('ready-to-show', () => {
            win.show();
        })
        win.loadFile('Local/index.html')
        win.on('closed', () => {
            win = null
        });
        winObj[winId] = win;
    };
    return win;
};

const gotTheLock = app.requestSingleInstanceLock()

if (!gotTheLock) {
    app.quit()
} else {
    app.on('second-instance', (event, commandLine, workingDirectory) => {
        var hasWin = null;
        for (const key in winObj) {
            if (winObj.hasOwnProperty(key)) {
                const win = winObj[key];
                if (win) {
                    hasWin = win;
                    break;
                };
            }
        };

        if (hasWin) {
            if (hasWin.isMinimized()) hasWin.restore()
            hasWin.focus();
        }
    })
    app.on('ready', () => {
        DB.init(async function (DB) {
            DB.all('SELECT * FROM project', function (err, res) {
                if (err) {
                    dialog.showErrorBox('Requester', '数据库读取出现错误');
                    app.quit();
                } else {
                    // var winId = 'Local' + '&' + res[0].project_id;
                    var data = {
                        projectId: res[0].project_id,
                        serviceId: 'Local',
                    };
                    createWindow(data);
                }
            });
        });
    })
};


app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
        app.quit()
    }
})

app.on('activate', () => {
    if (win === null) {
        createWindow()
    }
});